/*
 *                    COPYRIGHT NOTICE
 *
 *           This code is copyright protected by Freedom Inc.
 *
 *              2001-2012 All Rights Are Reserved
 */
package com.freedom.oldsong.filter;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.freedom.oldsong.common.AppConstants;
import com.freedom.oldsong.util.PrivilegeUtil;

/**
 * @author steven.wang
 *
 */
public class PrivilegeFilter implements Filter {
	
	private static final Logger logger=Logger.getLogger(PrivilegeFilter.class);
	
	private FilterConfig filterConfig;
	
	private static Map<String ,Properties> privilegeMap = new HashMap<String ,Properties>();
	
	private String onErrorUrl;
	
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse respone,
			FilterChain next) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpRespone = (HttpServletResponse)respone;
		String url = httpRequest.getRequestURL().toString();
		url=url.replace(AppConstants.getConfigValue(AppConstants.SERVER_ADRESS), "");
		String action = url.substring(0,url.indexOf("."+AppConstants.ACTION));
		String orgId = request.getParameter("orgId");
		String privileges=null;
		Iterator<String> it = privilegeMap.keySet().iterator();
		while(it.hasNext()){
			String key = it.next();
			Properties p = privilegeMap.get(key);
			privileges = (String)p.get(action);
			if(privileges!=null){
				break;
			}
		}
		if( privileges==null || PrivilegeUtil.hasAnyGroupRoleAndPrivilege(orgId,privileges)){
			next.doFilter(request, respone);
		}
		else{
			httpRespone.sendRedirect(AppConstants.getConfigValue(AppConstants.SERVER_ADRESS)+onErrorUrl);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		filterConfig = config;
        String propertyFiles=filterConfig.getInitParameter("propertyFiles");
        onErrorUrl=filterConfig.getInitParameter("onErrorUrl");
        if(onErrorUrl!=null&&!onErrorUrl.startsWith("/")){
        	onErrorUrl="/"+onErrorUrl;
        }
        if (propertyFiles!=null || !"".equals(propertyFiles)){
                String[] files = propertyFiles.split(",");
                for(String file:files){
                	loadProperties(file);
                }
        }
	}
	
	private static void loadProperties(String fileName){
		if(fileName==null || "".equals(fileName)){
			return;
		}
		try {
			int index = fileName.lastIndexOf('/');
			String namespace = "";
			String name = fileName;
			if(index>=0){
				namespace = name.substring(0, index+1);
				name=name.substring(index+1);
			}
			if(!namespace.startsWith("/")){
				namespace="/"+namespace;
			}
			InputStream in = PrivilegeFilter.class.getResourceAsStream(namespace+name);
			Properties p = new Properties();
			p.load(in);
			privilegeMap.put(namespace, p);
		} catch (IOException e) {
			logger.equals(e.getMessage());
		}
	}
}
